package com.isunland.managesystem.receiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.isunland.managesystem.service.LocationService;

/**
 * 外勤轨迹定时器
 */
public class AlarmReceiver extends BroadcastReceiver {

  /**
   * 判断 外勤自动记录轨迹 是否开启
   */
  public static boolean isServiceAlarmOn(Context context) {
    Intent i = new Intent(context, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_NO_CREATE);
    return pi != null;
  }

  /**
   * 启用外勤自动记录轨迹
   *
   * @param isOn 是否启动后台服务记录轨迹
   */
  public static void setServiceAlarm(Context context, boolean isOn) {
    Intent alarmIntent = new Intent(context, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    //LogUtil.i(TAG, "alarm=" + isOn);
    if (isOn) {

      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60, pi);
    } else {
      alarmManager.cancel(pi);
      pi.cancel();
      context.stopService(new Intent(context, LocationService.class));
    }

    //PreferenceManager.getDefaultSharedPreferences(context).edit()
    //        .putBoolean("isAlarmOn", isOn).commit();
  }

  public static void stopServiceAlarm(Context context) {
    //停止外勤轨迹服务.
    if (AlarmReceiver.isServiceAlarmOn(context)) {
      AlarmReceiver.setServiceAlarm(context, false);
    }
  }

  @Override public void onReceive(Context context, Intent intent) {

    context.startService(new Intent(context, LocationService.class));
  }
}